import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:fl_chart/fl_chart.dart';
import '../../../common/styles/theme_manager.dart';
import '../../../widgets/fixed_header_with_tabs.dart';
import 'dart:ui' as ui;
import 'blood_oxygen_logic.dart';
import '../calendar/simple_calendar_view.dart';

/// 血氧饱和度页面
class BloodOxygenView extends GetView<BloodOxygenLogic> {
  const BloodOxygenView({super.key});

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.black,
      body: SafeArea(
        child: Column(
          children: [
            // 固定的头部（标题 + 日周月切换）
            Obx(() => FixedHeaderWithTabs(
                  title: '血氧饱和度',
                  selectedIndex: _getSelectedIndex(),
                  onTabChanged: (index) {
                    switch (index) {
                      case 0:
                        controller.setTimeRange(BloodOxygenTimeRange.day);
                        break;
                      case 1:
                        controller.setTimeRange(BloodOxygenTimeRange.week);
                        break;
                      case 2:
                        controller.setTimeRange(BloodOxygenTimeRange.month);
                        break;
                    }
                  },
                  actions: [
                    IconButton(
                      icon: const Icon(Icons.stacked_bar_chart,
                          color: Colors.white),
                      onPressed: () {
                        Get.toNamed('/manual_measure',
                            arguments: {'type': 'bloodOxygen'});
                      },
                    ),
                    IconButton(
                      icon: const Icon(Icons.calendar_today,
                          color: Colors.white),
                      onPressed: () async {
                        final selectedDate = await Get.to(() =>
                            const SimpleCalendarView(
                                calendarType: CalendarType.bloodOxygen));
                        if (selectedDate != null && selectedDate is String) {
                          controller.loadDataByDate(selectedDate);
                        }
                      },
                    ),
                  ],
                )),
            // 可滚动的内容区域
            Expanded(
              child: SingleChildScrollView(
                child: Stack(
                  children: [
                    Positioned(
                      top: 0,
                      left: 0,
                      right: 0,
                      height: 240.h,
                      child: Container(
                        decoration: BoxDecoration(
                          gradient: LinearGradient(
                            begin: Alignment.topRight,
                            end: Alignment.bottomRight,
                            colors: ThemeManager.to.backgroundGradientColors,
                            stops: const [0.1, 0.3, 0.7, 1.0],
                          ),
                        ),
                      ),
                    ),
                    Padding(
                      padding: EdgeInsets.all(16.w),
                      child: Column(
                        crossAxisAlignment: CrossAxisAlignment.center,
                        children: [
                          SizedBox(height: 20.h),
                          _buildMainValue(),
                          SizedBox(height: 12.h),
                          _buildDateLine(),
                          SizedBox(height: 16.h),
                          _buildAreaChartCard(),
                          SizedBox(height: 16.h),
                          _buildManualMeasurementRecordsCard(), // 手动测量记录卡片（独立）
                          SizedBox(height: 16.h),
                          _buildMonthlyMonitorCard(),
                          SizedBox(height: 16.h),
                          _buildAboutCard(),
                          SizedBox(height: 40.h),
                        ],
                      ),
                    )
                  ],
                ),
              ),
            ),
          ],
        ),
      ),
    );
  }

  /// 获取当前选中的索引
  int _getSelectedIndex() {
    switch (controller.currentRange.value) {
      case BloodOxygenTimeRange.day:
        return 0;
      case BloodOxygenTimeRange.week:
        return 1;
      case BloodOxygenTimeRange.month:
        return 2;
    }
  }



  Widget _buildMainValue() {
    return Obx(() {
      // 使用monitorData的average字段
      final monitor = controller.monitorData.value;
      final avg = monitor?.average ?? 0;
      return Row(
        crossAxisAlignment: CrossAxisAlignment.end,
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          Text('$avg',
              style: TextStyle(
                  fontSize: 64.sp,
                  fontWeight: FontWeight.bold,
                  color: Colors.white)),
          SizedBox(width: 4.w),
          Padding(
            padding: EdgeInsets.only(bottom: 10.h),
            child: Text('% 全天平均值',
                style: TextStyle(fontSize: 16.sp, color: Colors.white)),
          ),
        ],
      );
    });
  }

  Widget _buildDateLine() {
    return Obx(() => Text(
          controller.getDateTitle(),
          style: TextStyle(fontSize: 14.sp, color: Colors.grey[400]),
        ));
  }

  /// 构建血氧趋势图卡片
  Widget _buildAreaChartCard() {
    return _buildSectionCard(
      title: '血氧趋势',
      child: _buildAreaChart(),
    );
  }

  Widget _buildAreaChart() {
    return Obx(() {
      final d = controller.monitorData.value;
      final timeRange = controller.currentRange.value;

      // 如果没有数据，显示空图表
      if (d == null ||
          (d.automaticInfoVOS.isEmpty && d.manualInfoVOS.isEmpty)) {
        return SizedBox(
          height: 200.h,
          child: Center(
            child: Text(
              '暂无数据',
              style: TextStyle(
                fontSize: 14.sp,
                color: Colors.grey[500],
              ),
            ),
          ),
        );
      }

      // 根据时间范围显示不同的图表
      if (timeRange == BloodOxygenTimeRange.day) {
        return _buildDayLineChart(d);
      } else {
        return _buildWeekMonthBarChart(d, timeRange);
      }
    });
  }

  /// 构建日视图折线图
  Widget _buildDayLineChart(BloodOxygenMonitorData d) {
    // 合并自动测量和手动测量数据
    final allDataPoints = <BloodOxygenDataPoint>[
      ...d.automaticInfoVOS,
      ...d.manualInfoVOS,
    ];

    // 将数据转换为图表格式（只包含有效数据点，value > 0）
    final chartData = <FlSpot>[];
    for (var point in allDataPoints) {
      // 只添加有效数据（value > 0）
      if (point.value != null && point.value! > 0) {
        // 解析时间 "HH:mm"
        final timeParts = point.code.split(':');
        if (timeParts.length == 2) {
          final hour = int.tryParse(timeParts[0]) ?? 0;
          final minute = int.tryParse(timeParts[1]) ?? 0;
          final timeInHours = hour + (minute / 60.0);
          chartData.add(FlSpot(timeInHours, point.value!.toDouble()));
        }
      }
    }

    // 按时间排序
    chartData.sort((a, b) => a.x.compareTo(b.x));

    return SizedBox(
      height: 380.h,
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          // 解读说明
          Container(
            padding: EdgeInsets.all(12.w),
            decoration: BoxDecoration(
              color: Colors.grey[800]?.withOpacity(0.3),
              borderRadius: BorderRadius.circular(8.r),
            ),
            child: Text(
              '解读：',
              style: TextStyle(
                fontSize: 13.sp,
                color: Colors.grey[400],
              ),
            ),
          ),
          SizedBox(height: 12.h),

          // 图例和正常范围说明
          Row(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: [
              // 左侧图例
              Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Row(
                    children: [
                      Container(
                        width: 8.w,
                        height: 8.w,
                        decoration: BoxDecoration(
                          color: Colors.grey[600],
                          shape: BoxShape.circle,
                        ),
                      ),
                      SizedBox(width: 4.w),
                      Text(
                        '其他时段血氧',
                        style: TextStyle(
                          fontSize: 12.sp,
                          color: Colors.grey[400],
                        ),
                      ),
                    ],
                  ),
                  SizedBox(height: 4.h),
                  Row(
                    children: [
                      Container(
                        width: 8.w,
                        height: 8.w,
                        decoration: BoxDecoration(
                          color: Colors.grey[400],
                          shape: BoxShape.circle,
                        ),
                      ),
                      SizedBox(width: 4.w),
                      Text(
                        '睡眠时血氧',
                        style: TextStyle(
                          fontSize: 12.sp,
                          color: Colors.grey[400],
                        ),
                      ),
                    ],
                  ),
                ],
              ),
              // 右侧正常范围说明
              Column(
                crossAxisAlignment: CrossAxisAlignment.end,
                children: [
                  Text(
                    '正常范围95%-100%',
                    style: TextStyle(
                      fontSize: 12.sp,
                      color: Colors.grey[400],
                    ),
                  ),
                  SizedBox(height: 4.h),
                  Text(
                    '异常值    <90%',
                    style: TextStyle(
                      fontSize: 12.sp,
                      color: Colors.grey[400],
                    ),
                  ),
                ],
              ),
            ],
          ),
          SizedBox(height: 12.h),

          // 图表 - 折线图
          Expanded(
            child: LineChart(
              LineChartData(
                gridData: FlGridData(
                  show: true,
                  drawVerticalLine: false,
                  horizontalInterval: 10,
                  getDrawingHorizontalLine: (value) {
                    return FlLine(
                      color: Colors.grey.withOpacity(0.2),
                      strokeWidth: 1,
                    );
                  },
                ),
                titlesData: FlTitlesData(
                  show: true,
                  rightTitles: AxisTitles(
                    sideTitles: SideTitles(showTitles: false),
                  ),
                  topTitles: AxisTitles(
                    sideTitles: SideTitles(showTitles: false),
                  ),
                  leftTitles: AxisTitles(
                    sideTitles: SideTitles(
                      showTitles: true,
                      interval: 10,
                      getTitlesWidget: (value, meta) {
                        if (value == 0 || value == 90 || value == 100) {
                          return Text(
                            '${value.toInt()}',
                            style: TextStyle(
                              color: Colors.grey[400],
                              fontSize: 10.sp,
                            ),
                          );
                        }
                        return const SizedBox.shrink();
                      },
                      reservedSize: 25.w,
                    ),
                  ),
                  bottomTitles: AxisTitles(
                    sideTitles: SideTitles(
                      showTitles: true,
                      interval: 24,
                      getTitlesWidget: (value, meta) {
                        if (value == 0) {
                          return Text(
                            '00:00',
                            style: TextStyle(
                              color: Colors.grey[400],
                              fontSize: 10.sp,
                            ),
                          );
                        } else if (value == 24) {
                          return Text(
                            '24:00',
                            style: TextStyle(
                              color: Colors.grey[400],
                              fontSize: 10.sp,
                            ),
                          );
                        }
                        return const SizedBox.shrink();
                      },
                      reservedSize: 20.h,
                    ),
                  ),
                ),
                borderData: FlBorderData(show: false),
                minX: 0,
                maxX: 24,
                minY: 0,
                maxY: 100,
                lineBarsData: [
                  LineChartBarData(
                    spots: chartData,
                    isCurved: false,
                    color: const Color(0xFFFF8C00),
                    barWidth: 2.w,
                    isStrokeCapRound: false,
                    dotData: FlDotData(
                      show: false,
                    ),
                    belowBarData: BarAreaData(
                      show: true,
                      gradient: LinearGradient(
                        begin: Alignment.topCenter,
                        end: Alignment.bottomCenter,
                        colors: [
                          const Color(0xFFFF8C00).withOpacity(0.4),
                          const Color(0xFFFF8C00).withOpacity(0.2),
                          const Color(0xFFFF8C00).withOpacity(0.1),
                        ],
                      ),
                    ),
                  ),
                ],
                lineTouchData: LineTouchData(
                  enabled: true,
                  touchTooltipData: LineTouchTooltipData(
                    getTooltipColor: (touchedSpot) => Colors.grey[800]!,
                    getTooltipItems: (touchedSpots) {
                      return touchedSpots.map((spot) {
                        final hour = spot.x.toInt();
                        final minute = ((spot.x - hour) * 60).toInt();
                        return LineTooltipItem(
                          '${hour.toString().padLeft(2, '0')}:${minute.toString().padLeft(2, '0')}\n${spot.y.toInt()}%',
                          TextStyle(
                            color: Colors.white,
                            fontSize: 12.sp,
                            fontWeight: FontWeight.w500,
                          ),
                        );
                      }).toList();
                    },
                  ),
                ),
              ),
            ),
          ),
          SizedBox(height: 16.h),

          // 显示最高和最低值
          Row(
            mainAxisAlignment: MainAxisAlignment.spaceAround,
            children: [
              Container(
                padding: EdgeInsets.symmetric(horizontal: 20.w, vertical: 12.h),
                decoration: BoxDecoration(
                  color: Colors.white.withOpacity(0.05),
                  borderRadius: BorderRadius.circular(12.r),
                ),
                child: Text(
                  '最低${d.minValue}%',
                  style: TextStyle(
                    fontSize: 14.sp,
                    color: Colors.grey[400],
                    fontWeight: FontWeight.w500,
                  ),
                ),
              ),
              Container(
                padding: EdgeInsets.symmetric(horizontal: 20.w, vertical: 12.h),
                decoration: BoxDecoration(
                  color: Colors.white.withOpacity(0.05),
                  borderRadius: BorderRadius.circular(12.r),
                ),
                child: Text(
                  '最高${d.maxValue}%',
                  style: TextStyle(
                    fontSize: 14.sp,
                    color: Colors.grey[400],
                    fontWeight: FontWeight.w500,
                  ),
                ),
              ),
            ],
          ),

          SizedBox(height: 16.h),

          // 开始测量按钮
          Obx(() => GestureDetector(
                onTap: () {
                  if (controller.ringController.isBloodOxygenMeasuring) {
                    controller.ringController.stopBloodOxygenMeasure();
                  } else {
                    controller.ringController.startBloodOxygenMeasure();
                  }
                },
                child: Container(
                  width: double.infinity,
                  height: 48.h,
                  decoration: BoxDecoration(
                    color: const Color(0xFFBEBEBE),
                    borderRadius: BorderRadius.circular(24.r),
                  ),
                  child: Center(
                    child: Text(
                      controller.ringController.isBloodOxygenMeasuring
                          ? '停止测量'
                          : '开始测量',
                      style: TextStyle(
                        fontSize: 14.sp,
                        color: Colors.black,
                        fontWeight: FontWeight.w500,
                      ),
                    ),
                  ),
                ),
              )),
        ],
      ),
    );
  }

  /// 构建手动测量记录卡片（独立卡片）
  Widget _buildManualMeasurementRecordsCard() {
    return Obx(() {
      final monitorData = controller.monitorData.value;
      if (monitorData == null || monitorData.manualInfoVOS.isEmpty) {
        return const SizedBox.shrink();
      }

      final isExpanded = false.obs;

      return _buildSectionCard(
        title: '当天测量记录 (${monitorData.manualInfoVOS.length})',
        child: Obx(() => Column(
          children: [
            GestureDetector(
              onTap: () => isExpanded.value = !isExpanded.value,
              child: Container(
                padding: EdgeInsets.symmetric(vertical: 8.h),
                child: Row(
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: [
                    Text(
                      isExpanded.value ? '收起' : '展开查看',
                      style: TextStyle(
                        fontSize: 14.sp,
                        color: Colors.grey[400],
                      ),
                    ),
                    SizedBox(width: 4.w),
                    Icon(
                      isExpanded.value ? Icons.keyboard_arrow_up : Icons.keyboard_arrow_down,
                      color: Colors.grey[400],
                      size: 20.sp,
                    ),
                  ],
                ),
              ),
            ),
            if (isExpanded.value) ...[
              SizedBox(height: 8.h),
              ConstrainedBox(
                constraints: BoxConstraints(maxHeight: 200.h),
                child: SingleChildScrollView(
                  child: Column(
                    children: monitorData.manualInfoVOS.map((record) {
                      return Container(
                        margin: EdgeInsets.only(bottom: 8.h),
                        padding: EdgeInsets.symmetric(horizontal: 12.w, vertical: 10.h),
                        decoration: BoxDecoration(
                          color: Colors.white.withOpacity(0.05),
                          borderRadius: BorderRadius.circular(8.r),
                        ),
                        child: Row(
                          mainAxisAlignment: MainAxisAlignment.spaceBetween,
                          children: [
                            Text(
                              record.code,
                              style: TextStyle(
                                fontSize: 13.sp,
                                color: Colors.grey[300],
                              ),
                            ),
                            Text(
                              '${record.value ?? 0}%',
                              style: TextStyle(
                                fontSize: 13.sp,
                                color: Colors.white,
                                fontWeight: FontWeight.w500,
                              ),
                            ),
                          ],
                        ),
                      );
                    }).toList(),
                  ),
                ),
              ),
            ],
          ],
        )),
      );
    });
  }

  /// 构建周/月视图柱状图
  Widget _buildWeekMonthBarChart(
      BloodOxygenMonitorData d, BloodOxygenTimeRange timeRange) {
    // 过滤有效数据（maxValue > 0 或 minValue > 0）
    final validData = d.automaticInfoVOS
        .where((point) => point.maxValue > 0 || point.minValue > 0)
        .toList();

    if (validData.isEmpty) {
      return SizedBox(
        height: 200.h,
        child: Center(
          child: Text(
            '暂无数据',
            style: TextStyle(
              fontSize: 14.sp,
              color: Colors.grey[500],
            ),
          ),
        ),
      );
    }

    return SizedBox(
      height: 300.h,
      child: Column(
        children: [
          // 柱状图
          Expanded(
            child: BarChart(
              BarChartData(
                alignment: BarChartAlignment.spaceAround,
                maxY: 100,
                minY: 0,
                barTouchData: BarTouchData(
                  enabled: true,
                  touchTooltipData: BarTouchTooltipData(
                    getTooltipColor: (group) => Colors.grey[800]!,
                    getTooltipItem: (group, groupIndex, rod, rodIndex) {
                      final point = validData[group.x.toInt()];
                      return BarTooltipItem(
                        '${point.code}\n最高: ${point.maxValue}%\n最低: ${point.minValue}%',
                        TextStyle(
                          color: Colors.white,
                          fontSize: 11.sp,
                        ),
                      );
                    },
                  ),
                ),
                titlesData: FlTitlesData(
                  show: true,
                  bottomTitles: AxisTitles(
                    sideTitles: SideTitles(
                      showTitles: true,
                      getTitlesWidget: (value, meta) {
                        final index = value.toInt();
                        if (index >= 0 && index < validData.length) {
                          final code = validData[index].code;
                          // 周视图显示星期，月视图显示日期
                          final label = timeRange == BloodOxygenTimeRange.week
                              ? _getWeekdayLabel(code)
                              : code.split('/').last; // 只显示日期数字
                          return Text(
                            label,
                            style: TextStyle(
                              color: Colors.grey[400],
                              fontSize: 10.sp,
                            ),
                          );
                        }
                        return const SizedBox.shrink();
                      },
                      reservedSize: 20.h,
                    ),
                  ),
                  leftTitles: AxisTitles(
                    sideTitles: SideTitles(
                      showTitles: true,
                      interval: 25,
                      getTitlesWidget: (value, meta) {
                        return Text(
                          '${value.toInt()}',
                          style: TextStyle(
                            color: Colors.grey[400],
                            fontSize: 10.sp,
                          ),
                        );
                      },
                      reservedSize: 25.w,
                    ),
                  ),
                  topTitles: AxisTitles(
                    sideTitles: SideTitles(showTitles: false),
                  ),
                  rightTitles: AxisTitles(
                    sideTitles: SideTitles(showTitles: false),
                  ),
                ),
                gridData: FlGridData(
                  show: true,
                  drawVerticalLine: false,
                  horizontalInterval: 25,
                  getDrawingHorizontalLine: (value) {
                    return FlLine(
                      color: Colors.grey.withOpacity(0.2),
                      strokeWidth: 1,
                    );
                  },
                ),
                borderData: FlBorderData(show: false),
                barGroups: List.generate(validData.length, (index) {
                  final point = validData[index];
                  return BarChartGroupData(
                    x: index,
                    barRods: [
                      BarChartRodData(
                        fromY: point.minValue.toDouble(),
                        toY: point.maxValue.toDouble(),
                        color: const Color(0xFFFF8C00),
                        width: 16.w,
                        borderRadius: BorderRadius.vertical(
                          top: Radius.circular(4.r),
                        ),
                      ),
                    ],
                  );
                }),
              ),
            ),
          ),
        ],
      ),
    );
  }

  /// 获取星期标签
  String _getWeekdayLabel(String code) {
    // code 格式: "10/26"
    // 需要根据日期计算星期
    final parts = code.split('/');
    if (parts.length == 2) {
      final month = int.tryParse(parts[0]) ?? 0;
      final day = int.tryParse(parts[1]) ?? 0;
      if (month > 0 && day > 0) {
        final date = DateTime(DateTime.now().year, month, day);
        const weekdays = ['日', '一', '二', '三', '四', '五', '六'];
        return weekdays[date.weekday % 7];
      }
    }
    return code;
  }

  /// 构建本月夜间血氧监测卡片
  Widget _buildMonthlyMonitorCard() {
    return _buildSectionCard(
      title: '本月夜间血氧监测',
      child: _buildMonthlyMonitor(),
    );
  }

  /// 构建本月夜间血氧监测
  Widget _buildMonthlyMonitor() {
    return Obx(() {
      final avgData = controller.averageData.value;

      // 默认显示标签，数据来了就显示数值
      final avgValue = avgData?.bloodOxygenAverage ?? 0;
      final minValue = avgData?.minBloodOxygen ?? 0;
      final rateValue = avgData?.bloodOxygenRate ?? 0;
      final effectiveMeasurement = avgData?.effectiveMeasurement ?? 0;
      final exceptionCount = avgData?.exceptionCount ?? 0;

      return Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          // 三个指标
          _buildMonitorItem(
            '睡眠时平均血氧饱和度',
            avgValue > 0 ? '$avgValue%' : '--',
            Colors.grey[600]!,
          ),
          SizedBox(height: 12.h),
          _buildMonitorItem(
            '睡眠时最低血氧饱和度',
            minValue > 0 ? '$minValue%' : '--',
            Colors.grey[600]!,
          ),
          SizedBox(height: 12.h),
          _buildMonitorItem(
            '睡眠时血氧的低血氧占比（TST90）',
            rateValue > 0 ? '$rateValue%' : '--',
            Colors.grey[600]!,
          ),
          SizedBox(height: 16.h),

          // 进度条区域
          Container(
            padding: EdgeInsets.all(16.w),
            decoration: BoxDecoration(
              color: const Color(0xFF282528),
              borderRadius: BorderRadius.circular(12.r),
            ),
            child: Column(
              children: [
                // 有效测量次数进度条
                Row(
                  children: [
                    Container(
                      width: 8.w,
                      height: 8.w,
                      decoration: const BoxDecoration(
                        color: Color(0xFF4A90E2),
                        shape: BoxShape.circle,
                      ),
                    ),
                    SizedBox(width: 8.w),
                    Expanded(
                      child: Text(
                        '总睡眠时间内有效测量次数',
                        style: TextStyle(
                          fontSize: 13.sp,
                          color: Colors.grey[400],
                        ),
                      ),
                    ),
                    Text(
                      '${effectiveMeasurement}次',
                      style: TextStyle(
                        fontSize: 14.sp,
                        color: Colors.white,
                        fontWeight: FontWeight.w600,
                      ),
                    ),
                  ],
                ),
                SizedBox(height: 12.h),

                // 异常次数进度条
                Row(
                  children: [
                    Container(
                      width: 8.w,
                      height: 8.w,
                      decoration: const BoxDecoration(
                        color: Color(0xFFFF9500),
                        shape: BoxShape.circle,
                      ),
                    ),
                    SizedBox(width: 8.w),
                    Expanded(
                      child: Text(
                        '血氧饱和度＜90%的次数',
                        style: TextStyle(
                          fontSize: 13.sp,
                          color: Colors.grey[400],
                        ),
                      ),
                    ),
                    Text(
                      '${exceptionCount}次',
                      style: TextStyle(
                        fontSize: 14.sp,
                        color: Colors.white,
                        fontWeight: FontWeight.w600,
                      ),
                    ),
                  ],
                ),
                SizedBox(height: 12.h),

                // 进度条可视化
                if (effectiveMeasurement > 0)
                  Stack(
                    children: [
                      // 背景条
                      Container(
                        height: 8.h,
                        decoration: BoxDecoration(
                          color: const Color(0xFF2A2A2A),
                          borderRadius: BorderRadius.circular(4.r),
                        ),
                      ),
                      // 蓝色进度条（有效测量）
                      FractionallySizedBox(
                        widthFactor: 1.0,
                        child: Container(
                          height: 8.h,
                          decoration: BoxDecoration(
                            color: const Color(0xFF4A90E2),
                            borderRadius: BorderRadius.circular(4.r),
                          ),
                        ),
                      ),
                      // 橙色进度条（异常次数）
                      if (exceptionCount > 0)
                        FractionallySizedBox(
                          widthFactor: (exceptionCount / effectiveMeasurement)
                              .clamp(0.0, 1.0),
                          alignment: Alignment.centerRight,
                          child: Container(
                            height: 8.h,
                            decoration: BoxDecoration(
                              color: const Color(0xFFFF9500),
                              borderRadius: BorderRadius.circular(4.r),
                            ),
                          ),
                        ),
                    ],
                  ),
              ],
            ),
          ),
          SizedBox(height: 16.h),

          // TST90说明
          Container(
            padding: EdgeInsets.all(12.w),
            decoration: BoxDecoration(
              color: const Color(0xFF282528),
              borderRadius: BorderRadius.circular(8.r),
            ),
            child: Text(
              'TST90=血氧饱和度＜90%的次数/总睡眠时间内有效测量次数*100%',
              style: TextStyle(
                fontSize: 12.sp,
                color: Colors.grey[500],
                height: 1.5,
              ),
            ),
          ),
        ],
      );
    });
  }

  /// 构建监测项
  Widget _buildMonitorItem(String title, String value, Color dotColor) {
    return Row(
      children: [
        Container(
          width: 8.w,
          height: 8.w,
          decoration: BoxDecoration(
            color: dotColor,
            shape: BoxShape.circle,
          ),
        ),
        SizedBox(width: 8.w),
        Expanded(
          child: Text(
            title,
            style: TextStyle(
              fontSize: 13.sp,
              color: Colors.grey[400],
            ),
          ),
        ),
        Text(
          value,
          style: TextStyle(
            fontSize: 14.sp,
            color: Colors.white,
            fontWeight: FontWeight.w600,
          ),
        ),
      ],
    );
  }

  /// 构建关于血氧数据卡片
  Widget _buildAboutCard() {
    return _buildSectionCard(
      title: '关于血氧数据',
      child: _buildAboutContent(),
    );
  }

  /// 构建关于血氧数据内容
  Widget _buildAboutContent() {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Text(
          'SPO2：血氧饱和度',
          style: TextStyle(
            fontSize: 14.sp,
            color: Colors.white,
            fontWeight: FontWeight.w600,
          ),
        ),
        SizedBox(height: 4.h),
        Text(
          '血氧饱和度是血液中被氧结合的血红蛋白所占的百分比，正常动脉血氧饱和度约为95% - 100%。',
          style: TextStyle(
            fontSize: 13.sp,
            color: Colors.grey[400],
            height: 1.5,
          ),
        ),
        SizedBox(height: 12.h),
        Text(
          '低血氧占比',
          style: TextStyle(
            fontSize: 14.sp,
            color: Colors.white,
            fontWeight: FontWeight.w600,
          ),
        ),
        SizedBox(height: 4.h),
        Text(
          '低血氧占比是指睡眠期间血氧饱和度低于90%的时间占总睡眠时间的百分比。正常情况下，这个比例应该小于5%。如果低血氧占比过高，可能提示存在睡眠呼吸暂停等问题，建议咨询医生。',
          style: TextStyle(
            fontSize: 13.sp,
            color: Colors.grey[400],
            height: 1.5,
          ),
        ),
      ],
    );
  }

  /// 通用分区卡片（参考睡眠页面样式）
  Widget _buildSectionCard({
    required String title,
    required Widget child,
    VoidCallback? onHelpTap,
  }) {
    return Container(
      decoration: BoxDecoration(
        color: const Color(0xff282528),
        borderRadius: BorderRadius.circular(20.r),
        border: Border.all(
          color: const Color.fromRGBO(33, 33, 33, 1),
          width: 1,
        ),
      ),
      child: Column(
        children: [
          Padding(
            padding: EdgeInsets.symmetric(horizontal: 12.w, vertical: 10.h),
            child: Row(
              children: [
                Text(
                  title,
                  style: TextStyle(
                    fontSize: 16.sp,
                    fontWeight: FontWeight.w600,
                    color: Colors.white,
                  ),
                ),
                const Spacer(),
                if (onHelpTap != null)
                  GestureDetector(
                    onTap: onHelpTap,
                    child: Icon(
                      Icons.help_outline,
                      color: Colors.white.withOpacity(0.9),
                      size: 18.sp,
                    ),
                  ),
              ],
            ),
          ),
          const Divider(
            height: 1,
            thickness: 1,
            color: Color(0xff353235),
          ),
          Padding(
            padding: EdgeInsets.all(12.w),
            child: child,
          ),
        ],
      ),
    );
  }
}
